<?php namespace App\Http\Controllers\Api;

use App\Activity;
use App\Doctors;
use App\Exceptions\NotFoundException;
use App\Exceptions\PaymentException;
use App\Exceptions\SecurityException;
use App\FollowQrcode;
use App\Orders;
use App\Packages;
use App\Referral;
use App\Services\UserManager;
use App\Services\Wechat\config;
use App\Services\Wechat\WechatLogin;
use App\Services\Wechat\WechatModelMsg;
use App\User;
use App\UserActivity;
use App\UserXDoctor;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Log;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Support\Collection;
use EasyWeChat\Payment\Order;

class WechatController extends ApiController
{
    public function index(){
        Log::info('request arrived.');
        $app    = app("wechat");
        $server = $app->server;
        $user = $app->user;
        $menu = $app->menu;
        $server->setMessageHandler(function($message) use ($user) {
            $fromUser = $user->get($message->FromUserName);
            $openid   = $message->FromUserName;
            switch($message->MsgType){
                case 'event':
                    if($message->Event == "subscribe"){
                        Log::error('aaaaa');
                        $eventKey = $message->EventKey;
                        $docId    = str_replace('qrscene_','',$eventKey);
                        /** @var User $thatUser */
                        $thatUser   = User::whereOpenid($openid)->first();
                        /** @var Doctors $thatDoctor */
                        $thatDoctor = Doctors::whereUserId($docId)->first();
                        if($thatDoctor){
                            if($thatUser){
                                /** @var UserXDoctor $hasFollow */
                                $hasFollow = UserXDoctor::whereUserId($thatUser->id)->whereDoctorId($docId)->first();

                                if(!$hasFollow){
                                    $hasFollow            = new UserXDoctor();
                                    $hasFollow->user_id   = $thatUser->id;
                                    $hasFollow->doctor_id = $docId;
                                    $hasFollow->save();
                                }
                            }else{
                                /** @var FollowQrcode $followQrcode */
                                $followQrcode = FollowQrcode::whereOpenid($openid)->whereDocId($docId)->whereStatus(0)->first();
                                if(!$followQrcode){
                                    $followQrcode = new FollowQrcode();
                                    $followQrcode->openid = $openid;
                                    $followQrcode->doc_id = $docId;
                                    $followQrcode->save();
                                }
                            }

                            return '您好，欢迎关注［桂林名医］公众号，并已成功关注['.$thatDoctor->doc_name.']医生，可在'."\n\n".'<a href="'.route('M.Home.newFollowDoctors').'">我的医生</a>'."\n\n".'查看关注医生列表！';
                        }else{
                            return "您好，欢迎关注！如果您医疗方面的疑问，可点击底部菜单（自助服务）进行在线咨询或预约挂号。\n\n 同时您也可以可点击底部菜单在线[预约挂号]、[预约缴费]";
                        }
                    }
                    break;
                case 'text':
                    return "感谢您的关注！";
                    break;
            }
        });
        Log::info('return response.');
        $buttons =[
                [
                    "name" => "联系医生",
                    "sub_button" => [
                        [
                            "type" => "view",
                            "name" => "我的医生",
                            "url"  => route('M.Home.newFollowDoctors'),
                        ],
                        [
                            "type" => "view",
                            "name" => "更多医生",
                            "url"  => route('M.Home.newDoctorList'),
                        ],
                    ]
                ],
                [
                    "name" => "就诊服务",
                    "sub_button" => [
                        [
                            "type" => "view",
                            "name" => "预约检查",
                            "url"  => route('M.Home.packages'),
                        ],
                        [
                            "type" => "view",
                            "name" => "医院转诊",
                            "url"  => route('M.Doctor.patientList'),
                        ],
                    ]
                ],
                [
                    "name" => "更多服务",
                    "sub_button" => [
                        [
                            "type" => "view",
                            "name" => "个人中心",
                            "url"  => route('M.Home.newUserCenter'),
                        ],
                        [
                            "type" => "view",
                            "name" => "医生参会",
                            "url"  => "http://meeting.51wenyisheng.com",
                        ],
                        [
                            "type" => "view",
                            "name" => "医生入口",
                            "url"  => route('M.Doctor.userCenter'),
                        ],
                        [
                            "type" => "view",
                            "name" => "资讯",
                            "url"  => 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI5ODU0NDMxMA==&scene=124#wechat_redirect',
                        ],
                        [
                            "type" => "view",
                            "name" => "关于我们",
                            "url"  => 'http://mp.weixin.qq.com/s/jv19iO_wR6qQttM7xJMeTA',
                        ],
                    ]
                ]
        ];
        $menu->add($buttons);
        $a = $server->serve();

        return $a;
    }

    public function pay(Guard $guard,Request $request){
        $orderNum = Input::get('order_num');

        $user = UserManager::isLogin($request);
        if (!$user){
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

            /** @var User $user */
        }


        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereOrderNum($orderNum)->whereIspay(0)->first();
        if(!$thatOrder)
            throw new NotFoundException(NotFoundException::OrderNotFound);

        $name = null;
        if($thatOrder->type == 'appoint'){
            $name = '普通门诊费';
        }else if($thatOrder->type == 'face'){
            $name = '专家面诊费';
        }else if($thatOrder->type == "referral"){
            $name = '转诊费用';
        }elseif($thatOrder->type == 'sign_up'){
            /** @var Activity $isActivity */
            $isActivity = Activity::whereId($thatOrder->activity_id)->whereStatus(1)->first();
            if(!$isActivity)
                return response()->json(['level' => 'error','message' => '活动已下架']);

            if(strtotime($isActivity->start_time) <= time())
                return response()->json(['level' => 'error','message' => '报名已停止']);

            if(strtotime($isActivity->end_time) <= time())
                return response()->json(['level' => 'error','message' => '活动已结束']);

            $isJoinActivity = UserActivity::whereUserId($user->id)->whereActivityId($isActivity->id)->whereOrderNum($thatOrder->order_num)->whereStatus(1)->first();
            if($isJoinActivity)
                return response()->json(['level' => 'error','message' => '您已经报名过了']);

            $joinNum = UserActivity::whereUserId($user->id)->whereStatus(1)->count();
            if($isActivity->max_join_num <= $joinNum)
                return response()->json(['level' => 'error','message' => '活动参与人数已满']);

            $name = '会议报名';
        }else{
            $name = '套餐缴费';
        }

        if($thatOrder->type == 'sign_up' && $thatOrder->order_price == 0){
            $thatOrder->ispay = 1;
            $thatOrder->status = 1;
            $thatOrder->save();

            /** @var UserActivity $thatJoinActivity */
            $thatJoinActivity = UserActivity::whereUserId($thatOrder->user_id)->whereActivityId($thatOrder->activity_id)->whereOrderNum($thatOrder->order_num)->whereStatus(0)->first();
            if($thatJoinActivity){
                $thatJoinActivity->status = 1;
                $thatJoinActivity->save();
            }else{
                throw new PaymentException(PaymentException::SystemError);
            }


            return response()->json(['level' => 'success','message' => '报名成功','data' => $thatOrder]);
        }

        $openId = $user->openid;
        $app = app("wechat");
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => $name,
            'detail'           => $name,
            'out_trade_no'     => $orderNum,
            'total_fee'        => $thatOrder->order_price * 100,
            'notify_url'       => route('Api.Wechat.payCallBack'),
            'openid'           => $openId,
        ];
        $payment = $app->payment;
        $order = new Order($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            return $this->buildResponse(trans('获取json成功'),json_decode($json));
        }else{
            return response()->json(['level' => 'error','message' => '订单生成失败','data' => $result]);
        }
    }

    public function payCallBack(){
        $app = app("wechat");

        $response = $app->payment->handleNotify(function($notify, $successful){
            Log::info('1111111111111=>'.$notify->out_trade_no);
            /** @var Orders $order */
            $order = Orders::whereOrderNum($notify->out_trade_no)->first();
            if (!$order) {
                return 'Order not exist.';
            }

            if ((int)$order->ispay == 1) {
                return true;
            }

            if ($successful) {
                $order->pay_time = date('Y-m-d H:i:s',time());
                $order->ispay = 1;
                $order->status = 1;

                if($order->type == "package" || $order->type == "appoint"){
                    /** @var Doctors $thatDoctor */
                    $thatDoctor = Doctors::find($order->doctor_id);

                    if($thatDoctor){
                        $thatDoctor->bespoke_count = (int)$thatDoctor->bespoke_count + 1;
                        $thatDoctor->all_amount = (float)$thatDoctor->all_amount + (float)$order->order_price;
                        $thatDoctor->has_amount = (float)$thatDoctor->has_amount + (float)$order->order_price;
                        $thatDoctor->save();
                    }

                    WechatModelMsg::sendAppointMsg($notify->out_trade_no,route('M.Home.orderList'));
                    WechatModelMsg::sendMsgToDoctor($notify->out_trade_no,route('M.Home.orderList'));
                }else if($order->type == "referral"){
                    $thatReferral = Referral::whereOrderNum($order->order_num)->first();
                    if($thatReferral){
                        $thatReferral->status = 1;
                        $thatReferral->save();

                        /** @var Doctors $thatDoctor */
                        $thatDoctor = Doctors::find($order->doctor_id);

                        $thatDoctor->all_amount = (float)$thatDoctor->all_amount + (float)$order->order_price;
                        $thatDoctor->has_amount = (float)$thatDoctor->has_amount + (float)$order->order_price;
                        $thatDoctor->save();
                    }
                }elseif($order->type == "sign_up"){
                    /** @var Activity $thatActivity */
                    $thatActivity = Activity::whereId($order->activity_id)->whereStatus(1)->first();
                    if($thatActivity){
                        /** @var UserActivity $thatJoinActivity */
                        $thatJoinActivity = UserActivity::whereUserId($order->user_id)->whereActivityId($order->activity_id)->whereOrderNum($order->order_num)->whereStatus(0)->first();
                        if($thatJoinActivity){
                            $thatJoinActivity->status = 1;
                            $thatJoinActivity->save();
                        }else{
                            throw new PaymentException(PaymentException::SystemError);
                        }

                    }else{
                        throw new PaymentException(PaymentException::ActivityNotObtained);
                    }
                }
            } else {
                $order->ispay = 0;
                $order->status = 0;
            }
            $order->save();
            return true;
        });
        return $response;
    }

    public function getJsApiPacket(Request $request){
        $info = WechatLogin::getTicketByAccessToken();
        $jsapiTicket = $info->getTicket();

        $nonceStr = WechatLogin::createNonceStr();

        $timestamp = time();

        $url = urldecode($request->get('url'));

        Log::error('link===>'.$url);

        $config = new config();
        $appid  = $config->getAppid();

        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return response()->json(['level'=>'success','data'=>$signPackage]);
    }
}